import datetime
import logging
import traceback
import pymysql

from core.config import Config
from core.util import Util


class Rider(object):
    def __init__(self):
        self.rider_num_1 = 0
        self.rider_num_2 = 0
        self.rider_num_3 = 0
        self.rider_num_4 = 0

    @classmethod
    def get_rider_num(cls, shop_id):
        # 骑手数
        rider_num_obj = Rider()

        # 连接数据库
        db = pymysql.connect(**Config.ofs_work_center)

        try:
            cursor = db.cursor()

            sql = """SELECT
                        account_id,
                        switch_status,
                        queue_up_time,
                        switch_time
                    FROM ofs_work_center.t_worker
                    WHERE 
                    available = 1
                    AND type = 0
                    AND is_working = 1
                    AND shop_id = %s
                    AND switch_status in (1,2,3,4)
                    """
            cursor.execute(sql, (shop_id))
            results = cursor.fetchall()

            # 解析数据
            now_timestamp = datetime.datetime.now().timestamp()
            for row in results:
                account_id = int(row["account_id"])
                switch_status = int(row["switch_status"])
                queue_up_time = Util.datetime_to_timestamp(row["queue_up_time"])
                switch_time = Util.datetime_to_timestamp(row["switch_time"])

                # 状态持续时间
                status_duration = -1
                if switch_status == 1 and queue_up_time is not None:
                    status_duration = now_timestamp - queue_up_time
                else:
                    status_duration = now_timestamp - switch_time

                if switch_status == 1:
                    rider_num_obj.rider_num_1 += 1

                if switch_status == 2:
                    rider_num_obj.rider_num_2 += 1

                if switch_status == 3 and status_duration <= 1 * 60 * 60:
                    rider_num_obj.rider_num_3 += 1

                if switch_status == 4 and status_duration <= 1 * 60 * 60:
                    rider_num_obj.rider_num_4 += 1

            return rider_num_obj
        except Exception as e:
            traceback.print_exc()
            logging.error(f"获取骑手数异常{e}")
        finally:
            db.close()